package org.example.service;


import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.example.api.CategoriesApi;
import org.example.common.Result;
import org.example.mapper.CategoriesMapper;
import org.example.model.Article;
import org.example.model.Categories;
import org.example.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Component
@Service(interfaceClass = CategoriesApi.class, version = "1.0.0", timeout = 35000)
public class CategoriesService implements CategoriesApi {
    private static final Object QUERY_ALL_CATEGORIES_BY_USER_ID = new Object();
    @Autowired
    private CategoriesMapper categoriesMapper;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public Result<List<Categories>> queryAllCategoriesByUserId(Long userId) {
        // categories:user:{userId}
        String key = "categories:user:" + userId;
        List<Categories> categories = redisUtil.getObject(key);
        if (CollectionUtils.isEmpty(categories)) {
            synchronized (QUERY_ALL_CATEGORIES_BY_USER_ID) {
                categories = redisUtil.getObject(key);
                if (CollectionUtils.isEmpty(categories)) {
                    categories = categoriesMapper.queryCategoriesByUserId(userId);
                    if (!CollectionUtils.isEmpty(categories)) {
                        redisUtil.setObject(key, categories, 60 * 1000);
                    }
                }
            }
        }
        return Result.ok(categories);
    }
}
